import { FunctionExecutor, FunctionCallResult, AIContext } from './aiFunctionRegistry'
import { taskFunctions } from './aiFunctionRegistry'
import { Task } from '../database/init'

// 创建任务执行器
export const createTaskExecutor: FunctionExecutor = {
  name: taskFunctions.createTask.name,
  description: taskFunctions.createTask.description,
  parameters: taskFunctions.createTask.parameters,
  execute: async (args: any, context: AIContext): Promise<FunctionCallResult> => {
    try {
      const { title, description, priority, dueDate, category, tags } = args
      
      // 验证必需参数
      if (!title) {
        return {
          success: false,
          error: '任务标题不能为空'
        }
      }

      // 创建任务对象
      const newTask: Partial<Task> = {
        title,
        description: description || '',
        status: 'todo',
        priority: priority || context.userPreferences?.defaultPriority || 'P1',
        category: category || context.userPreferences?.defaultCategory || 'other',
        tags: tags || [],
        completed: false,
        user_id: context.userId,
        board_position: 0,
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      }

      // 处理截止日期
      if (dueDate) {
        newTask.due_date = new Date(dueDate).toISOString()
      }

      // 使用真实的任务API
      const { getDatabase } = require('../database/init')
      const { v4: uuidv4 } = require('uuid')
      const { normalizeDueDate, normalizeTimestamp } = require('../utils/dateUtils')
      const db = getDatabase()
      
      // 生成唯一ID
      const id = uuidv4()
      const now = normalizeTimestamp(new Date())
      const normalizedDueDate = normalizeDueDate(dueDate)
      
      // 创建任务
      await db.query(`
        INSERT INTO tasks (
          id, title, description, due_date, reminder_minutes, priority, category, tags, notes, user_id,
          is_recurring, recurring_type, recurring_pattern, parent_recurring_id,
          status, board_position, created_at, updated_at
        ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18)
      `, [
        id, title, description || '', normalizedDueDate, 30, priority || 'P2', category || 'work', 
        tags || [], description || '', context.userId, false, null, null, 
        null, 'todo', 0, now, now
      ])
      
      // 返回创建的任务
      const savedTask = {
        id,
        title,
        description: description || '',
        dueDate: normalizedDueDate,
        priority: priority || 'P2',
        category: category || 'work',
        tags: tags || [],
        notes: description || '',
        status: 'todo',
        completed: false,
        createdAt: now,
        updatedAt: now
      }

      return {
        success: true,
        data: savedTask,
        message: `已创建任务"${title}"，优先级：${savedTask.priority}`
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : '创建任务失败'
      }
    }
  }
}

// 更新任务执行器
export const updateTaskExecutor: FunctionExecutor = {
  name: taskFunctions.updateTask.name,
  description: taskFunctions.updateTask.description,
  parameters: taskFunctions.updateTask.parameters,
  execute: async (args: any, context: AIContext): Promise<FunctionCallResult> => {
    try {
      const { taskId, updates } = args
      
      if (!taskId) {
        return {
          success: false,
          error: '任务ID不能为空'
        }
      }

      // 查找任务
      const task = context.currentTasks.find(t => t.id === taskId)
      if (!task) {
        return {
          success: false,
          error: '任务不存在'
        }
      }

      // 应用更新
      const updatedTask = {
        ...task,
        ...updates,
        updated_at: new Date().toISOString()
      }

      // 使用真实的任务API
      const { getDatabase } = require('../database/init')
      const { normalizeTimestamp, normalizeDueDate } = require('../utils/dateUtils')
      const db = getDatabase()
      const now = normalizeTimestamp(new Date())
      
      // 构建更新查询
      let updateQuery = 'UPDATE tasks SET updated_at = $1'
      const values = [now]
      let paramIndex = 2
      
      // 添加需要更新的字段
      if (updates.title !== undefined) {
        updateQuery += `, title = $${paramIndex}`
        values.push(updates.title)
        paramIndex++
      }
      if (updates.description !== undefined) {
        updateQuery += `, description = $${paramIndex}`
        values.push(updates.description)
        paramIndex++
      }
      if (updates.dueDate !== undefined) {
        updateQuery += `, due_date = $${paramIndex}`
        values.push(normalizeDueDate(updates.dueDate))
        paramIndex++
      }
      if (updates.priority !== undefined) {
        updateQuery += `, priority = $${paramIndex}`
        values.push(updates.priority)
        paramIndex++
      }
      if (updates.category !== undefined) {
        updateQuery += `, category = $${paramIndex}`
        values.push(updates.category)
        paramIndex++
      }
      if (updates.tags !== undefined) {
        updateQuery += `, tags = $${paramIndex}`
        values.push(updates.tags)
        paramIndex++
      }
      if (updates.status !== undefined) {
        updateQuery += `, status = $${paramIndex}`
        values.push(updates.status)
        paramIndex++
      }
      if (updates.completed !== undefined) {
        updateQuery += `, completed = $${paramIndex}`
        values.push(updates.completed)
        paramIndex++
      }
      
      // 添加WHERE条件
      updateQuery += ` WHERE id = $${paramIndex} AND user_id = $${paramIndex + 1}`
      values.push(taskId, context.userId)
      
      // 执行更新
      await db.query(updateQuery, values)
      
      // 获取更新后的任务
      const result = await db.query(`
        SELECT * FROM tasks WHERE id = $1 AND user_id = $2
      `, [taskId, context.userId])
      
      if (result.rows.length === 0) {
        return {
          success: false,
          error: '任务不存在或已被删除'
        }
      }
      
      const updatedTaskData = result.rows[0]
      
      return {
        success: true,
        data: {
          id: updatedTaskData.id,
          title: updatedTaskData.title,
          description: updatedTaskData.description,
          dueDate: updatedTaskData.due_date,
          priority: updatedTaskData.priority,
          category: updatedTaskData.category,
          tags: updatedTaskData.tags,
          status: updatedTaskData.status,
          completed: updatedTaskData.completed,
          createdAt: updatedTaskData.created_at,
          updatedAt: updatedTaskData.updated_at
        },
        message: `已更新任务"${updatedTaskData.title}"`
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : '更新任务失败'
      }
    }
  }
}

// 查询任务执行器
export const queryTasksExecutor: FunctionExecutor = {
  name: taskFunctions.queryTasks.name,
  description: taskFunctions.queryTasks.description,
  parameters: taskFunctions.queryTasks.parameters,
  execute: async (args: any, context: AIContext): Promise<FunctionCallResult> => {
    try {
      const { filters = {}, sortBy = 'created_at', limit = 10 } = args
      
      console.log(`[DEBUG] 查询任务 - 用户ID: ${context.userId}, 过滤器:`, filters)
      
      // 使用真实的任务API，增强过滤功能
      const { getDatabase } = require('../database/init')
      const db = getDatabase()
      
      // 构建查询条件
      let whereClause = 'WHERE t.user_id = $1'
      const queryParams = [context.userId]
      let paramIndex = 2
      
      // 添加过滤条件
      if (filters) {
        if (filters.status) {
          whereClause += ` AND t.status = $${paramIndex}`
          queryParams.push(filters.status)
          paramIndex++
        }
        if (filters.priority) {
          whereClause += ` AND t.priority = $${paramIndex}`
          queryParams.push(filters.priority)
          paramIndex++
        }
        if (filters.category) {
          whereClause += ` AND t.category = $${paramIndex}`
          queryParams.push(filters.category)
          paramIndex++
        }
          if (filters.dueDate) {
            // 处理日期范围查询
            if (filters.dueDate.startsWith('today')) {
              const today = new Date()
              today.setHours(0, 0, 0, 0)
              const todayStr = today.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
              }).replace(/\//g, '-')
              
              const tomorrow = new Date(today)
              tomorrow.setDate(tomorrow.getDate() + 1)
              const tomorrowStr = tomorrow.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
              }).replace(/\//g, '-')
              
              whereClause += ` AND t.due_date >= $${paramIndex} AND t.due_date < $${paramIndex + 1}`
              queryParams.push(todayStr)
              queryParams.push(tomorrowStr)
              paramIndex += 2
            } else if (filters.dueDate.startsWith('this_week')) {
              const today = new Date()
              const dayOfWeek = today.getDay()
              const startOfWeek = new Date(today)
              startOfWeek.setDate(today.getDate() - dayOfWeek)
              startOfWeek.setHours(0, 0, 0, 0)
              
              const endOfWeek = new Date(startOfWeek)
              endOfWeek.setDate(startOfWeek.getDate() + 7)
              
              const startStr = startOfWeek.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
              }).replace(/\//g, '-')
              
              const endStr = endOfWeek.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
              }).replace(/\//g, '-')
              
              whereClause += ` AND t.due_date >= $${paramIndex} AND t.due_date < $${paramIndex + 1}`
              queryParams.push(startStr)
              queryParams.push(endStr)
              paramIndex += 2
            }
          }
        if (filters.tags && Array.isArray(filters.tags) && filters.tags.length > 0) {
          whereClause += ` AND t.tags && $${paramIndex}::text[]`
          queryParams.push(filters.tags)
          paramIndex++
        }
      }
      
      // 构建排序条件
      let orderClause = 'ORDER BY '
      switch (sortBy) {
        case 'due_date':
          orderClause += 't.due_date ASC NULLS LAST'
          break
        case 'priority':
          orderClause += 't.priority ASC'
          break
        case 'title':
          orderClause += 't.title ASC'
          break
        default:
          orderClause += 't.created_at DESC'
      }
      
      // 执行查询
      const result = await db.query(`
        SELECT t.*, 
               COALESCE(
                 json_agg(
                   CASE WHEN s.id IS NOT NULL THEN 
                     json_build_object('id', s.id, 'title', s.title, 'completed', s.completed)
                   END
                 ) FILTER (WHERE s.id IS NOT NULL), 
                 '[]'
               ) as subtasks
        FROM tasks t
        LEFT JOIN subtasks s ON t.id = s.task_id
        ${whereClause}
        GROUP BY t.id
        ${orderClause}
        LIMIT $${paramIndex}
      `, [...queryParams, limit])
      
      const tasks = result.rows.map((row: any) => {
        // 删除原始的下划线字段，避免冲突
        const { 
          due_date, created_at, updated_at, user_id,
          is_recurring, recurring_type, recurring_pattern, parent_recurring_id,
          ...cleanRow 
        } = row
        
        return {
          ...cleanRow,
          dueDate: due_date,
          createdAt: created_at,
          updatedAt: updated_at,
          userId: user_id,
          isRecurring: is_recurring,
          recurringType: recurring_type,
          recurringPattern: recurring_pattern,
          parentRecurringId: parent_recurring_id
        }
      })

      console.log(`[DEBUG] 查询结果: 找到 ${tasks.length} 个任务`)

      return {
        success: true,
        data: {
          tasks: tasks,
          total: tasks.length,
          returned: tasks.length
        },
        message: `找到${tasks.length}个任务`
      }
    } catch (error) {
      console.error('[ERROR] 查询任务失败:', error)
      return {
        success: false,
        error: error instanceof Error ? error.message : '查询任务失败'
      }
    }
  }
}

// 完成任务执行器
export const completeTaskExecutor: FunctionExecutor = {
  name: taskFunctions.completeTask.name,
  description: taskFunctions.completeTask.description,
  parameters: taskFunctions.completeTask.parameters,
  execute: async (args: any, context: AIContext): Promise<FunctionCallResult> => {
    try {
      const { taskId, notes } = args
      
      if (!taskId) {
        return {
          success: false,
          error: '任务ID不能为空'
        }
      }

      // 查找任务
      const task = context.currentTasks.find(t => t.id === taskId)
      if (!task) {
        return {
          success: false,
          error: '任务不存在'
        }
      }

      // 更新任务状态
      const updatedTask = {
        ...task,
        status: 'done' as const,
        completed: true,
        updated_at: new Date().toISOString()
      }

      // 使用真实的任务API
      const { getDatabase } = require('../database/init')
      const { normalizeTimestamp } = require('../utils/dateUtils')
      const db = getDatabase()
      const now = normalizeTimestamp(new Date())
      
      // 更新任务状态为完成
      await db.query(`
        UPDATE tasks 
        SET status = 'done', completed = true, updated_at = $1
        WHERE id = $2 AND user_id = $3
      `, [now, taskId, context.userId])
      
      // 获取更新后的任务
      const result = await db.query(`
        SELECT * FROM tasks WHERE id = $1 AND user_id = $2
      `, [taskId, context.userId])
      
      if (result.rows.length === 0) {
        return {
          success: false,
          error: '任务不存在或已被删除'
        }
      }
      
      const completedTask = result.rows[0]
      
      return {
        success: true,
        data: {
          id: completedTask.id,
          title: completedTask.title,
          status: completedTask.status,
          completed: completedTask.completed,
          updatedAt: completedTask.updated_at
        },
        message: `已完成任务"${completedTask.title}"`
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : '完成任务失败'
      }
    }
  }
}

// 删除任务执行器
export const deleteTaskExecutor: FunctionExecutor = {
  name: taskFunctions.deleteTask.name,
  description: taskFunctions.deleteTask.description,
  parameters: taskFunctions.deleteTask.parameters,
  execute: async (args: any, context: AIContext): Promise<FunctionCallResult> => {
    try {
      const { taskId } = args
      
      if (!taskId) {
        return {
          success: false,
          error: '任务ID不能为空'
        }
      }

      // 查找任务
      const task = context.currentTasks.find(t => t.id === taskId)
      if (!task) {
        return {
          success: false,
          error: '任务不存在'
        }
      }

      // 使用真实的任务API
      const { getDatabase } = require('../database/init')
      const db = getDatabase()
      
      // 先删除子任务
      await db.query('DELETE FROM subtasks WHERE task_id = $1', [taskId])
      
      // 再删除任务
      await db.query('DELETE FROM tasks WHERE id = $1 AND user_id = $2', [taskId, context.userId])
      
      return {
        success: true,
        data: { 
          taskId,
          title: task.title
        },
        message: `已删除任务"${task.title}"`
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : '删除任务失败'
      }
    }
  }
}

// 获取任务统计执行器
export const getTaskStatsExecutor: FunctionExecutor = {
  name: taskFunctions.getTaskStats.name,
  description: taskFunctions.getTaskStats.description,
  parameters: taskFunctions.getTaskStats.parameters,
  execute: async (args: any, context: AIContext): Promise<FunctionCallResult> => {
    try {
      const { period = 'week' } = args
      
      // 使用真实的任务API获取统计信息
      const { getDatabase } = require('../database/init')
      const db = getDatabase()
      const now = new Date()
      
      // 获取基本统计
      const basicStatsQuery = await db.query(`
        SELECT 
          COUNT(*) as total,
          SUM(CASE WHEN status = 'todo' THEN 1 ELSE 0 END) as pending,
          SUM(CASE WHEN status = 'in_progress' THEN 1 ELSE 0 END) as in_progress,
          SUM(CASE WHEN status = 'done' OR completed = true THEN 1 ELSE 0 END) as completed,
          SUM(CASE WHEN due_date::timestamp < $1 AND (status != 'done' AND completed = false) THEN 1 ELSE 0 END) as overdue,
          SUM(CASE WHEN priority = 'P0' THEN 1 ELSE 0 END) as high_priority
        FROM tasks
        WHERE user_id = $2
      `, [now.toISOString(), context.userId])
      
      // 获取今天到期的任务
      const today = new Date()
      today.setHours(0, 0, 0, 0)
      const tomorrow = new Date(today)
      tomorrow.setDate(tomorrow.getDate() + 1)
      
      const dueTodayQuery = await db.query(`
        SELECT COUNT(*) as due_today
        FROM tasks
        WHERE user_id = $1
          AND due_date::timestamp >= $2
          AND due_date::timestamp < $3
          AND (status != 'done' AND completed = false)
      `, [context.userId, today.toISOString(), tomorrow.toISOString()])
      
      // 获取分类统计
      const categoryStatsQuery = await db.query(`
        SELECT 
          category,
          COUNT(*) as count
        FROM tasks
        WHERE user_id = $1
        GROUP BY category
      `, [context.userId])
      
      // 整合统计结果
      const basicStats = basicStatsQuery.rows[0]
      const dueToday = dueTodayQuery.rows[0].due_today
      const categoryStats = categoryStatsQuery.rows.reduce((acc: any, row: any) => {
        acc[row.category] = row.count
        return acc
      }, {})
      
      const stats = {
        total: parseInt(basicStats.total) || 0,
        pending: parseInt(basicStats.pending) || 0,
        inProgress: parseInt(basicStats.in_progress) || 0,
        completed: parseInt(basicStats.completed) || 0,
        overdue: parseInt(basicStats.overdue) || 0,
        highPriority: parseInt(basicStats.high_priority) || 0,
        dueToday: parseInt(dueToday) || 0,
        categories: categoryStats
      }

      return {
        success: true,
        data: stats,
        message: `任务统计：总计${stats.total}个，待办${stats.pending}个，进行中${stats.inProgress}个，已完成${stats.completed}个，逾期${stats.overdue}个`
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : '获取统计信息失败'
      }
    }
  }
}

// 导出所有执行器
export const taskExecutors = [
  createTaskExecutor,
  updateTaskExecutor,
  queryTasksExecutor,
  completeTaskExecutor,
  deleteTaskExecutor,
  getTaskStatsExecutor
]
